package com.ywjt.platformbusiness.my.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.base.BaseModel;
import com.ywjt.platformbusiness.common.MethodUtils;
import com.ywjt.platformbusiness.common.UserData;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.login.LoginActivity;
import com.ywjt.platformbusiness.util.GlideEngine;
import com.ywjt.platformbusiness.util.JsonUtils;
import com.ywjt.platformbusiness.util.PictureUtils;
import com.ywjt.platformbusiness.util.ToastUtil;
import com.ywjt.platformbusiness.widget.PhotoPickBottomDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ActivitySet  extends BaseActivity implements View.OnClickListener {
    private LinearLayout llNickNameModify,llPwdModify;
    private TextView tvChangePhoto,tvExit;
private ImageView ivHeadLink;

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, ActivitySet.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llNickNameModify:
                ActivityNickNameModify.actionStart(this);
                break;
            case R.id.llPwdModify:
                ActivityPwdModify.actionStart(this);
                break;
            case R.id.tvChangePhoto:
                PhotoPickBottomDialog dialog=new PhotoPickBottomDialog();
                dialog.setClicklistener(new PhotoPickBottomDialog.ClickListenerInterface() {
                    @Override
                    public void takePhoto() {
                        PictureSelector.create(ActivitySet.this)
                                .openGallery(PictureMimeType.ofImage())
                                .selectionMode(PictureConfig.SINGLE)
                                .isCamera(true)
                                .compressQuality(100)
                                .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                .forResult(PictureConfig.REQUEST_CAMERA);
                    }

                    @Override
                    public void selectFromAlbum() {
                        PictureSelector.create(ActivitySet.this)
                                .openGallery(PictureMimeType.ofImage())
                                .selectionMode(PictureConfig.SINGLE)
                                .isCamera(false)
                                .compressQuality(100)
                                .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    }
                });
                dialog.show(getSupportFragmentManager());
                break;
            case R.id.tvExit:
                MethodUtils.logoutAfter(this);
                LoginActivity.actionStart(this);
                finish();
                break;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_set;
    }

    @Override
    protected void initView() {
        setTitleText("设置");
        llNickNameModify=findViewById(R.id.llNickNameModify);
        llPwdModify=findViewById(R.id.llPwdModify);
        tvChangePhoto=findViewById(R.id.tvChangePhoto);
        tvExit=findViewById(R.id.tvExit);
        ivHeadLink=findViewById(R.id.ivHeadLink);
        tvExit.setOnClickListener(this::onClick);
        tvChangePhoto.setOnClickListener(this::onClick);
        llNickNameModify.setOnClickListener(this::onClick);
        llPwdModify.setOnClickListener(this::onClick);
    }

    @Override
    protected void initData() {
        Glide.with(ActivitySet.this).load(UserData.create(ActivitySet.this).get(UserData.AVATAR))
                .placeholder(R.mipmap.default_headlink)
                .apply(new RequestOptions().transform(new PictureUtils()))
                .into(ivHeadLink);
    }

    /**
     * 获取要使用的标题栏样式(此函数由子类重写)
     *
     * @return
     */
    @Override
    protected int getTitleBarType() {
        return 0;
    }

    String path="";
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                case PictureConfig.REQUEST_CAMERA:
                    // 结果回调
                    List<LocalMedia> cameraList = PictureSelector.obtainMultipleResult(data);
                    if(cameraList.size()>0){
                        path=cameraList.get(0).getRealPath();
                    }
                    Glide.with(ActivitySet.this).load(path)
                            .placeholder(R.mipmap.default_headlink)
                            .apply(new RequestOptions().transform(new PictureUtils()))
                            .into(ivHeadLink);
                    uploadImg(path);
                    break;
                default:
                    break;
            }
        }
    }

    public void uploadImg(String path){
        new HttpRequest(ActivitySet.this).doUploadFile(UrlConstants.common_upload, "", "file", new File(path), new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model=(BaseModel) obj;
                            submit(model.getMessage());
                        }
                    }else {
                        ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, message, 1);
                        toastUtil.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

    public  void submit(String headImg) {
        JSONObject map = new JSONObject();
        try {
            map.put("avatar", headImg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new HttpRequest(ActivitySet.this).doPost(UrlConstants.user_modifyAvatar, null, map,new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        UserData.create(ActivitySet.this).changeUserData(UserData.AVATAR,headImg);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.e("ActivitySet",msg);
            }
        });
    }

}
